<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试Netty实现的websocket</title>
</head>
<body>
<textarea id="tx">

</textarea>

<script>
    var socket;
    if (window.WebSocket) {
        var host = window.location.hostname;
        console.log(host)
        var url = "ws://" + host + ":8111/ws";
        socket = new WebSocket(url);
        // if (socket.readyState==WebSocket.OPEN) {
        //     console.log("打印输出")
        //     socket.send(JSON.stringify("Hello xiaoliang@qq.com"));
        // }else{
        //     //do something
        // }
        var count = 0;
        setInterval(function () {
            send("Hello xiaoliang@qq.com, this is " + count);
            count++;
        }, 5000);
        socket.onmessage = function(e){
            //当客户端收到服务端发来的消息时，触发onmessage事件，参数e.data包含server传递过来的数据
            console.log(e.data);
            document.getElementById("tx").innerHTML = document.getElementById("tx").innerHTML +"\r\n"+ e.data;
        }
    } else {
        alert("你的浏览器不支持WebSocket。请不要使用低版本的IE浏览器。");
    }


    //发送数据
    function send(message) {
        if (!window.WebSocket) {
            return;
        }

        //当websocket状态打开
        if (socket.readyState == WebSocket.OPEN) {
            socket.send(message);
        } else {
            console.log("连接没有开启");
        }
    }
</script>
</body>
</html>